#ifndef __UDSF_RTC_C_
#define __UDSF_RTC_C_

#include "app.h"

/*
*   notice:
*   UDSF 同UDF编程：不可调用cstd-lib,只可调用"sdk_ifs_udk_cfg.h"、"sys_api.h"中列出的API函数。
*   UDSF文件内函数均需使用static修饰符，且UDF中以#include "udsf_xxx.c"形式引用
*/
#include "udsf_sys_api.c"
static void udsf_rtc_set(uint8_t id,uint32_t value) __attribute__((unused));
static int udsf_rtc_get_block(uint8_t id,int (*pFun_callback)(void)) __attribute__((unused));
static uint32_t udsf_rtc_timeit(int id,uint32_t init_ok,uint32_t init_value) __attribute__((unused));

static uint32_t udsf_rtc_timeit(int id,uint32_t init_ok,uint32_t init_value)
{
	RTC_T *  rtc[] = {RTC0,RTC1};
	uint32_t mask[] = {RTC0_PATTERN_SW_Msk,RTC1_PATTERN_SW_Msk};

	if( !init_ok ){
		SYSC->CLK_EN &= ~mask[id]; // rtc clk enable
		rtc[id]->CMP = 0xFFFF;
		rtc[id]->WKU_CFG = 0x00;                // BIT1:1,repeat 0,single   BIT0:1,cmp*1024 0,cmp*1	
		rtc[id]->CLR = RTC_CLR_Msk;  // clear  rtc cnt
	}
	else{
		init_value = rtc[id]->CNT0>>5;
		rtc[id]->CLR = RTC_CLR_Msk;  // clear  rtc cnt
	}
	return init_value;
}

static int udsf_rtc_get(uint8_t id){
	
	int ret = 0;
	
	RTC_T *  rtc[] = {RTC0,RTC1};
	
	if(rtc[id]->IRQ_CFG & 0x1ul)
	{
		ret = 1;
	}

	return ret;
}

static void udsf_rtc_set(uint8_t id,uint32_t value){

	RTC_T *  rtc[] = {RTC0,RTC1};
	uint32_t mask[] = {RTC0_PATTERN_SW_Msk,RTC1_PATTERN_SW_Msk};
		
	SYSC->CLK_EN &= ~mask[id]; // rtc1 clk enable
	rtc[id]->CMP = value;
	rtc[id]->CLR = RTC_CLR_Msk;  // clear  rtc1 cnt
	rtc[id]->IRQ_CFG |= RTC_IRQ_CLEAR_Msk;  // rtc1 irq flag clear
	rtc[id]->IRQ_CFG &= ~RTC_IRQ_MASK_Msk;  // rtc1 irq enable
	rtc[id]->WKU_CFG = 0x00;                // BIT1:1,repeat 0,single   BIT0:1,cmp*1024 0,cmp*1
}

static int udsf_rtc_get_block(uint8_t id,int (*pFun_callback)(void)){
	
	int ret = 0;
	
	RTC_T *  rtc[] = {RTC0,RTC1};
	uint32_t mask[] = {RTC0_PATTERN_SW_Msk,RTC1_PATTERN_SW_Msk};
	
	while ((rtc[id]->IRQ_CFG & 0x1ul) == 0) { //wait rtc0 irq
		if( pFun_callback() ){
			ret = 1;
			break;
		}
	}
	rtc[id]->IRQ_CFG |= RTC_IRQ_MASK_Pos;   // rtc0 irq disable
	rtc[id]->IRQ_CFG |= RTC_IRQ_CLEAR_Msk;  // rtc0 irq flag clear
	SYSC->CLK_EN  |= mask[id];// rtc0 clk disable

	return ret;
}

#endif
